import { acceptHMRUpdate, defineStore } from 'pinia'
import { type Mode as HeaderMode, MODE_DEFAULT } from './header'
import { WATERMARK_PARAM } from './constant'
import { getBasePath, getCompany } from '~/service'

export const useGlobalStore = defineStore('global', () => {
  // 图片域名
  const basePath = ref(API_URL)
  const company = ref({})
  async function initBasePath() {
    const result = await getBasePath()
    if (result)
      basePath.value = result as unknown as string
  }
  async function initCompany() {
    const result = await getCompany()
    if (result)
      company.value = result as unknown as string
  }
  function resolveImgURL(path: string) {
    if (!path)
      return ''
    return `${basePath.value}/${path}${WATERMARK_PARAM}`
  }

  // header 模式: 透明还是浅色
  const headerMode = ref<HeaderMode>(MODE_DEFAULT)
  function changeHeaderMode(nextMode: HeaderMode) {
    headerMode.value = nextMode
  }

  // 当 search 开启时，不能切换 header mode，将需要切换的 mode 保存起来
  const pendingHeaderMode = ref<Mode | undefined>(undefined)
  function restoreNextMode(pendingMode: Mode | undefined) {
    pendingHeaderMode.value = pendingMode
  }

  // search 是否可见
  const searchVisible = ref(false)
  function changeSearchVisible(nextVisible: boolean) {
    searchVisible.value = nextVisible
  }
  function toggleSearchVisible() {
    searchVisible.value = !searchVisible.value
  }

  // 初始化异步状态
  function init() {
    return Promise.allSettled([initBasePath(), initCompany()])
  }

  return {
    basePath,
    headerMode,
    pendingHeaderMode,
    searchVisible,
    company,
    init,
    changeHeaderMode,
    changeSearchVisible,
    resolveImgURL,
    restoreNextMode,
    toggleSearchVisible,
  }
})

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useGlobalStore, import.meta.hot))
